<template>
	<view>
		<view class="uni-header">
			<view class="uni-group">
				<view class="uni-title"></view>
				<view class="uni-sub-title"></view>
			</view>
			<view class="uni-group">
				<button class="uni-button" :type="where.indexOf('state==0')!= -1 ?'primary' :'default'" size="mini" @click="search('state==0')">待付款</button>
				<button class="uni-button" :type="where.indexOf('state==1')!= -1 ?'primary' :'default'" size="mini" @click="search('state==1')">待发货</button>
				<button class="uni-button" :type="where.indexOf('state==2')!= -1 ?'primary' :'default'" size="mini" @click="search('state==2')">待收货</button>
				<button class="uni-button" :type="where.indexOf('state==3')!= -1 ?'primary' :'default'" size="mini" @click="search('state==3')">待评价</button>
				<button class="uni-button" :type="where.indexOf('state<0')!= -1 ?'primary' :'default'" size="mini" @click="search('state<0')">已取消</button>

				<input class="uni-search margin-left-sm" type="text" v-model="query" @confirm="search()" placeholder="请输入搜索内容" />
				<button class="uni-button" type="default" size="mini" @click="search()">搜索</button>
			</view>
		</view>
		<view class="uni-container">
			<unicloud-db ref="udb" collection="cloud_orders,cloud_shops,uni-id-users" field="id,address,body,cancelApply,cancelStyle,cartCount,deliveryHour,deliveryType,freight,goods,isDelete,payInfo,juli,lastPayTime,platform,remark,shopid{id,name},state,totalDiscount,totalMoney,uid{nickname}"
			 :where="where" page-data="replace" :orderby="orderby" :getcount="true" :page-size="options.pageSize" :page-current="options.pageCurrent"
			 v-slot:default="{data,pagination,loading,error,options}" :options="options" @load="load">
				<view class="uni-pagination-box margin-bottom-sm margin-top-sm">
					<uni-pagination show-icon :page-size="pagination.size" v-model="pagination.current" :total="pagination.count"
					 @change="onPageChanged" />
				</view>
				<uni-table :loading="loading" :emptyText="error.message || '没有更多数据'" border stripe type="selection"
				 @selection-change="selectionChange">
					<uni-tr>
						<uni-th align="center">购买商品</uni-th>
						<uni-th align="center">订单号</uni-th>
						<uni-th align="center">购买用户</uni-th>
						<uni-th align="center">优惠金额</uni-th>
						<uni-th align="center">总金额</uni-th>
						<uni-th align="center">支付状态</uni-th>
						<uni-th align="center">订单状态</uni-th>
						<uni-th align="center">店铺</uni-th>
						<uni-th width="204" align="center">操作</uni-th>
					</uni-tr>
					<uni-tr v-for="(item,index) in data" :key="index">
						<uni-td align="" width="400">
							<view v-for="(item2,index2) in item.goods" :key="index2" class="flex margin-bottom-sm align-center">
								<image :src="item2.src" mode="aspectFill" class="suoluetu"></image>
								<view class="flex-sub flex flex-direction margin-left-sm">
									<view class="">
										<text>编号：{{item2.id}}</text>
										<text class="margin-left-sm">数量：{{item2.amount}}</text>
									</view>
									<text>{{item2.title}}</text>
								</view>
							</view>
						</uni-td>
						<uni-td align="center"> {{item.id}} </uni-td>
						<uni-td align="center"> {{item.uid[0] && (item.uid[0].nickname || "匿名")}} </uni-td>
						<uni-td align="center"> {{item.totalDiscount}} </uni-td>
						<uni-td align="center"> {{item.totalMoney}} </uni-td>
						<uni-td align="center"> {{item.payInfo?"已支付":"未支付"}} </uni-td>
						<uni-td align="center"><text class="important">{{item.stateTip}}</text> </uni-td>
						<uni-td align="center"> {{item.shopid[0] && item.shopid[0].name}} </uni-td>
						<uni-td align="center">
							<view class="uni-group">
								<button @click="delivery(item)" class="uni-button" size="mini" type="primary" v-if="$hasPermission('orders/addDelivery')  && item.state ==1">发货</button>
								<button @click="close(item)" class="uni-button" size="mini" type="warn" v-if="$hasPermission('orders/cancel') && item.state ==0">取消</button>
								<button @click="selftake(item)" class="uni-button" size="mini" type="primary" v-if="$hasPermission('orders/selftake') && item.state ==2">提货</button>
								<button @click="printOrder(item)" class="uni-button" size="mini" type="primary" v-if="$hasPermission('orders/printOrder')">打印小票</button>
								<button @click="detail(item)" class="uni-button" size="mini">详情</button>
								<!-- <button @click="navigateTo('./edit?id='+item._id, false)" class="uni-button" size="mini">查看</button> -->
							</view>
						</uni-td>
					</uni-tr>
				</uni-table>
				<view class="uni-pagination-box">
					<uni-pagination show-icon :page-size="pagination.size" v-model="pagination.current" :total="pagination.count"
					 @change="onPageChanged" />
				</view>
			</unicloud-db>
		</view>
		<uni-popup ref="popup" type="dialog">
			<view class="bg-white padding radius order-dialog">
				<view class="title">
					<text>订单信息</text>
				</view>
				<view class="">
					<view class="">
						<text>订单编号：</text>
						<text>{{orderInfo.id}}</text>
					</view>
					<view class="">
						<text>创建时间：</text>
						<uni-dateformat :date="orderInfo.created" :threshold="[0, 0]" format="yyyy-MM-dd hh:mm:ss"/>
					</view>
					<view class="">
						<text>备注：</text>
						<text v-if="orderInfo.remark">{{orderInfo.remark}}</text>
						<text v-else>无</text>
					</view>
				</view>
				<view class="title">
					<text>收货信息</text>
				</view>
				<view class="flex flex-direction" v-if="orderInfo.address && orderInfo.address.address">
					<text class="">收货人：{{orderInfo.address.name}}</text>
					<text class="">电话：{{orderInfo.address.mobile}}</text>
					<view class="">
						<text>地址：</text>
						<text>{{orderInfo.address.addressName}}</text>
						<text>{{orderInfo.address.address}}</text>
						<text>{{orderInfo.address.area}}</text>
					</view>
					<text class="">距离：{{orderInfo.juli}}米</text>
				</view>
				<view class="title">
					<text>配送</text>
				</view>
				<block v-if="orderInfo.deliveryHour">
					<view class="">
						<text>配送方式：</text>
						<text class="">{{options.deliveryType_valuetotext[orderInfo.deliveryType]}}</text>
					</view>
					<view class="">
						<text>日期：</text>
						<text>{{ orderInfo.deliveryHour.id  | dateFormat('yyyy-MM-dd hh:mm:ss')}}</text>
					</view>
					<view class="">
						<text>配送时段：</text>
						<text class="margin-left-sm">{{orderInfo.deliveryHour.time}}</text>
					</view>
				</block>
				<view class="title">
					<text>商品信息</text>
				</view>
				<view v-for="(item2,index2) in orderInfo.goods" :key="index2" class="flex margin-bottom-sm">
					<image :src="item2.src" mode="aspectFill" class="suoluetu"></image>
					<view class="flex-sub flex flex-direction margin-left-sm">
						<text>{{item2.title}}</text>
						<view class="">
							<text>编号：{{item2.id}}</text>
							<text v-if="item2.upc" class=" margin-left-sm">UPC：{{item2.upc}}</text>
						</view>
						<view class="">
							<text class="">数量：{{item2.amount}}</text>
							<text class=" margin-left-sm">价格：{{item2.price}}</text>
						</view>
					</view>
				</view>
				<view class="">
					<text>商品总价：</text>
					<text class="">{{orderInfo.totalMoney}}</text>
				</view>
				<view class="">
					<text>优惠金额：</text>
					<text class="">{{orderInfo.totalDiscount}}</text>
				</view>
				<view>
					<text>总数量：</text>
					<text class="">{{orderInfo.cartCount}}</text>
				</view>
				<block v-if="orderInfo.payInfo">
					<view class="title">
						<text>支付信息</text>
					</view>
					<view class="weui-flex">
						<text>支付方式：</text><text>{{ orderInfo.payInfo.name }}</text>
					</view>
					<view class="weui-flex">
						<text>支付时间：</text>
						<text>{{ orderInfo.payInfo.time   | dateFormat('yyyy-MM-dd hh:mm:ss')}}</text>
					</view>
				</block>
				<view class="text-center padding-top-sm">
					<button @click="closePop()" class="uni-button" size="mini" type="primary">确定</button>
				</view>
			</view>
		</uni-popup>
	</view>
</template>

<script>
	import {
		enumConverter
	} from '../../js_sdk/validator/cloud_orders.js';
	import {
		navToPayOrder,
		navToOrderGoodsList,
		miaoshaCountDown,
		navToOrderDetail,
		getOrderStateExp,
		clearCountDownTimer
	} from '@/common/js/functions.js';
	import uniPopup from '@/components/uni-popup/uni-popup.vue'
	import uniPopupDialog from '@/components/uni-popup/uni-popup-dialog.vue'
	import {
		orderAdmin
	} from '@/common/js/admin_request.js'

	const db = uniCloud.database()
	// 表查询配置
	const dbOrderBy = 'id desc' // 排序字段
	const dbSearchFields = [] // 模糊搜索字段，支持模糊搜索的字段列表
	// 分页配置
	const pageSize = 20
	const pageCurrent = 1

	export default {
		components: {
			uniPopup,
			uniPopupDialog
		},
		data() {
			return {
				query: '',
				where: 'state==1',
				orderby: dbOrderBy,
				options: {
					pageSize,
					pageCurrent,
					...enumConverter
				},
				orderInfo: {},
				imageStyles: {
					width: 64,
					height: 64
				}
			}
		},
		methods: {
			getWhere() {
				const query = this.query.trim()
				if (!query) {
					return ''
				}
				const queryRe = new RegExp(query, 'i')
				return dbSearchFields.map(name => queryRe + '.test(' + name + ')').join(' || ')
			},
			search(where) {
				let newWhere = this.getWhere();
				if (where) {
					if (newWhere) {
						newWhere = `(${newWhere}) && ${where}`;
					} else {
						newWhere = where;
					}
				}
				const isSameWhere = newWhere === this.where
				this.where = newWhere
				if (isSameWhere) { // 相同条件时，手动强制刷新
					this.loadData()
				}
			},
			load(data) {
				console.log("load", data)
				data.forEach(item => {
					getOrderStateExp(item)
				})
				console.log(this.options)
			},
			loadData(clear = true) {
				this.$refs.udb.loadData({
					clear
				})
			},
			onPageChanged(e) {
				this.$refs.udb.loadData({
					current: e.current
				})
			},
			navigateTo(url, clear) {
				// clear 表示刷新列表时是否清除页码，true 表示刷新并回到列表第 1 页，默认为 true
				uni.navigateTo({
					url,
					events: {
						refreshData: () => {
							this.loadData(clear)
						}
					}
				})
			},
			// 多选处理
			selectedItems() {
				var dataList = this.$refs.udb.dataList
				return this.selectedIndexs.map(i => dataList[i]._id)
			},
			//批量删除
			delTable() {
				this.$refs.udb.remove(this.selectedItems())
			},
			// 多选
			selectionChange(e) {
				this.selectedIndexs = e.detail.index
			},
			confirmDelete(id) {
				this.$refs.udb.remove(id)
			},
			close(item) {
				orderAdmin("cancel", item, true).then(res => {
					item.state = -1;
					getOrderStateExp(item)
					uni.showToast({
						title: '取消成功'
					})
				})
			},
			delivery(item) {
				orderAdmin("addDelivery", item, true).then(res => {
					item.state = 2;
					getOrderStateExp(item)
					uni.showToast({
						title: '发货成功'
					})
				})
			},
			selftake(item) {
				orderAdmin("selftake", item, true).then(res => {
					item.state = 3;
					getOrderStateExp(item)
					uni.showToast({
						title: '提货成功'
					})
				})
			},
			printOrder(item) {
				orderAdmin("printOrder", item, true).then(res => {
					uni.showToast({
						title: '小票打印成功'
					})
				})
			},
			detail(item) {
				this.orderInfo = item;
				this.$refs.popup.open()
			},
			closePop() {
				this.$refs.popup.close();
			}
		}
	}
</script>
<style lang="scss">
	.title {
		font-weight: 600;
		margin-top: 18rpx;
		font-size: 1.2em;
	}
</style>
